<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>切换图片定时器</title>
    <style>
      img {
        width: 400px;
        height: 300px;
      }
    </style>
  </head>
  <body>
    <img id="image" src="../JavaScript之DOM对象/images/img1.png" />
    <br /><br />

    <button id="start">开始</button>
    <button id="end">结束</button>

    <script>
      var image = document.getElementById("image");
      var imgArrs = [
        "../JavaScript之DOM对象/images/img1.png",
        "../JavaScript之DOM对象/images/img2.png",
        "../JavaScript之DOM对象/images/img3.png",
        "../JavaScript之DOM对象/images/img4.png",
        "../JavaScript之DOM对象/images/img5.png"
      ];
      var timer;
      var index = 0;

      var start = document.getElementById("start");
      var end = document.getElementById("end");

      // 点击开始，开启定时器循环展示图片
      start.onclick = function () {
        clearInterval(timer); // 结束上一个定时器

        timer = setInterval(function () {
          index++;
          index %= imgArrs.length; // 当index大于imgArrs.length时重置

          image.src = imgArrs[index];
        }, 1000);
      };

      // 点击结束，关闭定时器
      end.onclick = function () {
        clearInterval(timer);
      };
    </script>
  </body>
</html>
